﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CDFWPUG.Model;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using WP7Contrib.Collections;
using CDFWPUG.Objects;

namespace CDFWPUG.Helpers
{
    public class AppHelper
    {
        public AppHelper()
        {
            
        }
        
        public static UserApp GetUserApplicationByID(string xml, int id)
        {
            IEnumerable<UserApp> list = ParseUserApps(xml);

            var apps = from a in list
                       where a.ID == id.ToString()
                       select a;

            return apps.First();  
        }

        public static List<UserApp> SelectFeaturedApps(string xml, int count)
        {
            List<UserApp> myList = ParseUserApps(xml).ToList();
            List<UserApp> featuredItems = new List<UserApp>();

            if (count == 0)
            {
                featuredItems = myList;
            }
            else
            {
                Random myRandom = new Random();
                int index;

                while (featuredItems.Count < count)
                {
                    index = myRandom.Next(0, myList.Count() - 1);
                    featuredItems.Add(myList[index]);
                    myList.RemoveAt(index);
                    if (myList.Count() == 0)
                    {
                        break;
                    }
                }
            }
            return featuredItems.ToList();
        }

        public static ObservableCollection<UserApp> SelectFeaturedApps(List<UserApp> myList, int count)
        {
            List<UserApp> featuredItems = new List<UserApp>();

            if (count == 0)
            {
                featuredItems = myList;
            }
            else
            {
                Random myRandom = new Random();
                int index;

                while (featuredItems.Count < count)
                {
                    index = myRandom.Next(0, myList.Count() - 1);
                    featuredItems.Add(myList[index]);
                    myList.RemoveAt(index);
                    if (myList.Count() == 0)
                    {
                        break;
                    }
                }
            }
            return new ObservableCollection<UserApp> (featuredItems.ToList());
        }
   
        public static ObservableCollection<UserApp> GetFeaturedUserApps(int count)
        {
            List<UserApp> featuredItems;
            ObservableCollection<UserApp> list;
            var resource = System.Windows.Application.GetResourceStream(new Uri("Data/UserApps.xml", UriKind.Relative));
            StreamReader streamReader = new StreamReader(resource.Stream);
            string x = streamReader.ReadToEnd();
            featuredItems = SelectFeaturedApps(x, count);
            list = new ObservableCollection<UserApp>(featuredItems);
            return list;
        }

        public static ObservableCollection<GroupedObservableCollection<UserApp>> GetGroupedUserApps(ObservableCollection<UserApp> InitialContactsList)
        {
            //Initialise the Grouped OC to populate and return
            ObservableCollection<GroupedObservableCollection<UserApp>> GroupedApps = new ObservableCollection<GroupedObservableCollection<UserApp>>();

            //first sort our contacts collection into a temp List using LINQ
            var SortedList = (from con in InitialContactsList
                              orderby con.Name
                              select con).ToList();

            //Now enumerate throw the alphabet creating empty groups objects
            //This ensure that the whole alphabet exists even if we never populate them
            string Alpha = "#abcdefghijklmnopqrstuvwxyz";
            foreach (char c in Alpha)
            {
                //Create GroupedOC for given letter
                GroupedObservableCollection<UserApp> thisGroupOfApps = new GroupedObservableCollection<UserApp>(c.ToString());

                //Create a temp list with the appropriate Contacts that have this NameKey
                var SubsetOfCons = (from con in SortedList
                                    where con.NameKey == c.ToString()
                                    select con).ToList<UserApp>();

                //Populate the GroupedOC
                foreach (UserApp csm in SubsetOfCons)
                {
                    thisGroupOfApps.Add(csm);
                }

                //Add this GroupedOC to the observable collection that is being returned
                // and the LongListSelector can be bound to.
                GroupedApps.Add(thisGroupOfApps);
            }
            return GroupedApps;


        }

        public static ObservableCollection<UserApp> Test_GetFeaturedUserApps(int count)
        {
            List<UserApp> featuredItems;
            ObservableCollection<UserApp> list;
            var resource = System.Windows.Application.GetResourceStream(new Uri("Data/UserApps.xml", UriKind.Relative));
            StreamReader streamReader = new StreamReader(resource.Stream);
            string x = streamReader.ReadToEnd();
            featuredItems = SelectFeaturedApps (x, count);
            list = new ObservableCollection<UserApp>(featuredItems);
            return list;

        }

        public static ObservableCollection<UserApp> GetAppsFromIsolatedStorage()
        {
            string xml = Helpers.IsolatedStorageHelper.LoadFile("userapps.xml");
            var results = ParseUserApps(xml);
            return results;
        }

        public static ObservableCollection<UserApp> ParseUserApps(string xml)
        {
            XElement xmlApps = XElement.Parse(xml);
            var results = (from item in xmlApps.Descendants("app")
                                     select new UserApp
                                     {
                                         ID = item.Element("id").Value,
                                         ApplicationID = item.Element("appid").Value,
                                         Description = item.Element("description").Value,
                                         Price = item.Element("price").Value,
                                         Name = item.Element("name").Value,
                                         UserName = item.Element("developername").Value,
                                         ImageUrl = item.Element("iconurl").Value


                                     }).ToList();
            return new ObservableCollection<UserApp>(results);
        }

    }
}
